# !/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import json
from xtls.logger import get_logger

from company_xsb_handler import XsbBaseHandler
from cleaner import clean_str_null

reload(sys)
sys.setdefaultencoding('utf-8')

class BriefHandler(XsbBaseHandler):
    def __init__(self, stock, data, tab_op):
        logger = get_logger(__file__)
        super(BriefHandler, self).__init__(stock, data, tab_op, logger)
        self.tab_name = 'brief'

    def parse(self):
        return self.data_transfer(self.data)

    def data_transfer(self, data):
        db_data = dict()
        db_data['companyFullName'] = data.get('name', '')  # 公司全称
        db_data['companyName'] = data.get('shortname', '')  # 公司简称
        db_data['companyEnglishName'] = data.get('englishName', '')  # 英文名称
        db_data['regAddress'] = data.get('address', '')  # 注册地址
        db_data['legalPerson'] = data.get('legalRepresentative', '')  # 法定代表人
        db_data['secretary'] = data.get('secretaries', '')  # 公司董秘
        db_data['industry'] = data.get('industry', '')  # 行业种类
        db_data['zipcode'] = data.get('postcode', '')  # 邮政编码
        db_data['phone'] = data.get('phone', '')  # 公司电话
        db_data['fax'] = data.get('fax', '')  # 公司传真
        db_data['website'] = data.get('website', '')  # 公司网址
        db_data['listingDate'] = data.get('listingDate', '')  # 挂牌日期
        db_data['transferMode'] = data.get('transferMode', '')  # 转让方式
        db_data['broker'] = data.get('broker', '')  # 主办券商
        db_data['totalShare'] = data.get('totalStockEquity', '')  # 总股本
        db_data['province'] = data.get('area', '').replace(u'省', '').replace(u'市', '')

        return clean_str_null(db_data)

    def clean_data(self, dirty_data):
        self.cleaner.set_dirty_data(dirty_data)
        self.cleaner.clean_remove_http(['website'])
        self.cleaner.clean_get_id_single(['industry', 'broker', 'transferMode'],
                                    conn=self.conn)
        single_clean = self.cleaner.complete()
        single_clean['primaryIndustryId'] = self.get_primary_industry_id(dirty_data.get('industry'))
        single_clean['province'] = self._clean_province(single_clean.get('province'))
        return single_clean

    def _clean_province(self, province):
        if not province:
            return

        for short_name in [u'内蒙', u'广西', u'新疆', u'宁夏', u'西藏',]:
            if short_name in province:
                return short_name
        else:
            return province

    def get_primary_industry_id(self, industry):
        if industry:
            sql = 'SELECT primary_industry_id FROM company_relation_industry_primary_industry WHERE industry_name=%s'
            self.cur.execute(sql, (industry, ))
            return self.cur.fetchone()[0]

    def save_update(self, data):
        single = data

        if not single:
            self.logger.warn('brief has no information %s-%s' % (self.stock.id, self.stock.stock_code))
            return
        if not self.stock.id:
            return

        version_num = 1 + self.select_current_version_num(table_name=self.tab_name,
                                                          stock_id=self.stock.id)
        single_clean = self.clean_data(single)
        single_clean['stockId'] = self.stock.id
        single_clean['versionNum'] = version_num
        self.insert_to_db(table_name=self.tab_name, cleaned_data=single_clean)

    def save_print(self, data):
        clean_data = self.clean_data(data)
        print json.dumps(clean_data, indent=4)
        # raw_input()

